import BaseObj from "../BaseObj";

export default class ImageObj extends BaseObj {

    image: HTMLImageElement;
    imgPath: string
    width: number
    height: number
    loadSucess: boolean = false
    constructor(imgPath: string) {
        super()
        this.imgPath = imgPath
        this.image = new Image()
        this.image.onerror = this.imageLoadError.bind(this)
        this.image.onload = this.defaultOnload.bind(this)
        this.image.src = this.imgPath
    }

    onload(callback: (ev: Event) => any) {
        this.image.onload = (ev) => {
            this.defaultOnload(ev)
            callback(ev)
        }
    }

    protected defaultOnload(en: Event) {
        this.loadSucess = true
        this.width = this.image.width
        this.height = this.image.height
    }

    imageLoadError(ev: string | Event, error: Error | undefined) {
        console.error("图片 "+(<any>(<Event>ev).composedPath()[0]).currentSrc+" 加载失败！");
    }

    draw(ctx: CanvasRenderingContext2D) {
        if (!this.loadSucess) return

        ctx.drawImage(this.image, this.x, this.y,this.width,this.height)
    }


}